package com.r2coding.system.service.impl;

import com.r2coding.common.exception.BizCode;
import com.r2coding.common.exception.ServiceException;
import com.r2coding.common.util.Query;
import com.r2coding.system.dao.PermissionDao;
import com.r2coding.system.model.RolePermissionModel;
import com.r2coding.system.model.UserRoleModel;
import com.r2coding.system.service.UserService;
import com.r2coding.system.vo.req.AddUserRoleReqVo;
import com.r2coding.system.vo.req.QueryRoleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.r2coding.common.util.PageUtils;

import com.r2coding.system.dao.RoleDao;
import com.r2coding.system.entity.RoleEntity;
import com.r2coding.system.service.RoleService;
import org.springframework.util.CollectionUtils;

/**
 * 
 *
 * @author 98k灬
 * @email hk666zx@163.com
 * @date 2022-04-04 11:10:29
 */
@Slf4j
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleDao, RoleEntity> implements RoleService {
    @Autowired
    private PermissionDao permissionDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<RoleEntity> page = this.page(
                new Query<RoleEntity>().getPage(params),
                new QueryWrapper<RoleEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public void addUserRole(AddUserRoleReqVo vo) {
        Integer userId = vo.getUserId();
        // 将该用户的所有角色信息全部删除
        this.baseMapper.deleteByUserId(userId);
        // 重新添加角色信息
        List<UserRoleModel> collect = vo.getRoleIds().stream().map(roleId -> {
            UserRoleModel userRoleModel = new UserRoleModel();
            userRoleModel.setUserId(userId).setUpdateTime(new Date()).setCreateTime(new Date()).setRoleId(roleId);
            return userRoleModel;
        }).collect(Collectors.toList());

        for (UserRoleModel userRoleModel : collect) {
            this.baseMapper.addUserRole(userRoleModel);
        }
    }

    @Override
    public PageUtils queryAll(QueryRoleVo vo) {
        QueryWrapper<RoleEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(vo.getRoleName())) {
            wrapper.like("role_name", vo.getRoleName());
        }
        if (StringUtils.isNotEmpty(vo.getRoleDescription())) {
            wrapper.like("role_description", vo.getRoleDescription());
        }
        IPage<RoleEntity> page = baseMapper.selectPage(vo.getPage(), wrapper);
        return new PageUtils(page);
    }

    @Override
    public void removeRole(Integer roleId) {
        // 查询该角色有没有被某个用户使用 使用了就不能删除
        List<UserRoleModel> list = this.baseMapper.getByRoleId(roleId);
        if (!CollectionUtils.isEmpty(list)) {
            throw new ServiceException(BizCode.SERVICE_EXCEPTION);
        }
        this.baseMapper.deleteById(roleId);
    }

    @Override
    public void saveRole(RoleEntity role) {
        RoleEntity roleEntity = this.baseMapper.selectByRoleName(role.getRoleName());
        if (roleEntity == null) {
            // 新增
            role.setDeleted(0);
            role.setCreateTime(new Date());
            role.setUpdateTime(new Date());
            this.baseMapper.insert(role);
        } else {
            // 更新
            roleEntity.setDeleted(0);
            roleEntity.setRoleDescription(role.getRoleDescription());
            this.baseMapper.updateRoleById(roleEntity);
        }
    }

    //@Cacheable(value = "role", key = " #root.methodName + '_' + #roleId")
    @Override
    public List<Integer> getPermissionIdsByRoleId(Integer roleId) {
        return permissionDao.getPermissionIdsByRoleId(roleId).stream().map(RolePermissionModel::getPermissionId).collect(Collectors.toList());
    }
}